package com.pearlsoft.webapp.core.web.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;

import com.pearlsoft.webapp.core.web.session.SessionProfile;

/**
 * 
 * @Creator haitingr
 * @Create-Date 2010-12-28
 */
public abstract class HttpUtil {

	public static HttpSession getSession(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			session = request.getSession(true);
		}
		return session;
	}

	public static SessionProfile getUserProfileVO(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return null;
		}
		return getUserProfile(session);
	}

	public static SessionProfile getUserProfile(HttpSession session) {
		return (SessionProfile) session.getAttribute(SessionProfile.PROFILE_TAG);
	}

	public static void setUserProfile(HttpSession session, SessionProfile user) {
		session.setAttribute(SessionProfile.PROFILE_TAG, user);
	}

	public static void removeUserProfileVO(HttpSession session) {
		session.removeAttribute(SessionProfile.PROFILE_TAG);
	}

	public static Object getRequestAttribute(HttpServletRequest request, String key) {
		return request.getAttribute(key);
	}

	public static void setRequestAttribute(HttpServletRequest request, String key, Object value) {
		request.setAttribute(key, value);
	}

	public static String getRequestParameter(HttpServletRequest request, String key) {
		String value = request.getParameter(key);
		return value;
	}
	
	
	
	/**
	 * 返回cookie值  并解密
	 * @param request
	 * @param name
	 * @return
	 */
	
	public static String  getCookieValueByName(HttpServletRequest request,String name) {
		Cookie cookie = getCookieByName(request,name);
		if(cookie!=null){
			return new String(Base64.decodeBase64(cookie.getValue().getBytes()));
		}
		return null;
	}
	
	/**
	 * 根据Cookie Name 获取CooKie
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request,String name){
		 Map<String,Cookie> cookieMap  = getCookiesMap(request);
		 if(cookieMap.containsKey(name)){
			 Cookie cookie = (Cookie)cookieMap.get(name);
			 return cookie;
		 }
		return null;
	}
	
	
	
	/**
	 * 使用 KEY-VALUE 方式保持请求cookie
	 * @param request
	 * @return
	 */
	public static Map<String, Cookie> getCookiesMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}

}
